"use client";

import React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { ScrollArea } from '@/components/ui/scroll-area';
import { getAllVendorsContractsCompletionSummary } from '@/lib/forms/vendor-completion-stats';
import { Loader, Users, RefreshCw } from 'lucide-react';
import { toast } from 'sonner';

interface VendorProgress {
  vendorId: number;
  vendorName: string;
  totalForms: number;
  tagCount: number;
  totalRequiredFields: number;
  totalFilledFields: number;
  completionPercentage: number;
}

export default function EDPProgressTestPage() {
  const [loading, setLoading] = React.useState(false);
  const [vendorProgress, setVendorProgress] = React.useState<VendorProgress[]>([]);

  const loadVendorProgress = async () => {
    setLoading(true);
    
    try {
      const result = await getAllVendorsContractsCompletionSummary();
      
      if (result && result.vendors) {
        const progressData: VendorProgress[] = result.vendors.map(vendor => ({
          vendorId: vendor.vendorId,
          vendorName: vendor.vendorName,
          totalForms: vendor.totalForms,
          tagCount: vendor.totalTags,
          totalRequiredFields: vendor.totalRequiredFields,
          totalFilledFields: vendor.totalFilledFields,
          completionPercentage: vendor.overallCompletionPercentage
        }));
        
        setVendorProgress(progressData);
        toast.success(`${progressData.length}개 벤더의 진척도를 불러왔습니다`);
      } else {
        toast.warning('벤더 데이터가 없습니다');
      }
    } catch (error) {
      console.error('Error loading vendor progress:', error);
      toast.error(`벤더 진척도 로드 실패: ${error instanceof Error ? error.message : '알 수 없는 오류'}`);
    } finally {
      setLoading(false);
    }
  };

  React.useEffect(() => {
    loadVendorProgress();
  }, []);

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="flex items-center justify-between mb-6">
        <div className="flex items-center gap-2">
          <Users className="h-6 w-6" />
          <h1 className="text-3xl font-bold">벤더 진척도 현황</h1>
        </div>
        <Button 
          onClick={loadVendorProgress} 
          disabled={loading}
          className="flex items-center gap-2"
        >
          {loading ? <Loader className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
          새로고침
        </Button>
      </div>

      {/* Vendor Progress List */}
      <Card>
        <CardHeader>
          <CardTitle>벤더별 작업 진척도</CardTitle>
        </CardHeader>
        <CardContent>
          {loading ? (
            <div className="flex items-center justify-center py-8">
              <Loader className="h-6 w-6 animate-spin mr-2" />
              <span>벤더 진척도를 불러오는 중...</span>
            </div>
          ) : vendorProgress.length === 0 ? (
            <div className="text-center py-8 text-muted-foreground">
              벤더 데이터가 없습니다.
            </div>
          ) : (
            <div className="space-y-2">
              {/* Header */}
              <div className="grid grid-cols-6 gap-4 p-3 bg-muted rounded-lg font-semibold text-sm">
                <div>벤더명</div>
                <div className="text-center">폼 개수</div>
                <div className="text-center">태그 개수</div>
                <div className="text-center">전체 필드</div>
                <div className="text-center">입력 필드</div>
                <div className="text-center">완성도</div>
              </div>
              
              {/* Vendor Rows */}
              <ScrollArea className="h-96">
                <div className="space-y-1">
                  {vendorProgress.map((vendor) => (
                    <div key={vendor.vendorId} className="grid grid-cols-6 gap-4 p-3 border rounded-lg hover:bg-muted/50">
                      <div className="font-medium">{vendor.vendorName}</div>
                      <div className="text-center">{vendor.totalForms}</div>
                      <div className="text-center">{vendor.tagCount}</div>
                      <div className="text-center">{vendor.totalRequiredFields}</div>
                      <div className="text-center">{vendor.totalFilledFields}</div>
                      <div className="text-center">
                        <Badge 
                          variant={
                            vendor.completionPercentage >= 80 ? "default" : 
                            vendor.completionPercentage >= 50 ? "secondary" : 
                            "destructive"
                          }
                        >
                          {vendor.completionPercentage}%
                        </Badge>
                      </div>
                    </div>
                  ))}
                </div>
              </ScrollArea>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}